#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include"Protocol.hpp"

using namespace std;
#define NUM 1024

class Calclient
{
public:
    Calclient(const std::string serverip, const uint16_t serverport) : _serverip(serverip), _serverport(serverport), _sock(-1)
    {
    }
    void initClient()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(2);
        }

    }
    void start()
    {  struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        if(connect(_sock,(struct sockaddr*)&server,sizeof(server))!=0)
        {
            std::cerr << "socket connect error" << std::endl;
        }
        else
        { std::string s;
          std::string inbuffer;
            while(true)
            {  //1.发信息
                std::cout<<"enter";
                std::getline(std::cin,s);
                request req=parseline(s);
                string message;
                req.serialize(&message);
                string reqmessage=enlength(message);
                send(_sock,reqmessage.c_str(),reqmessage.size(),0);
                string respmessage;
               if(!recvmessage(_sock,&respmessage,&inbuffer)) continue;
               string re;
               if(!delength(respmessage,&re)) continue;
               response resp;
               resp.deserialize(re);
               cout<<resp.exitcode<<endl;
               cout<<resp.result<<endl;

                
                
               
            }
            
        }
         
    }
   static request parseline(string &s)
    { int i=0;
      int cnt=s.size();
      int status=0;//0表示x，1表示运算符，2表示y
      string left,right;
      char op;
      while(i<cnt)
      { switch(status)
        {   
            case 0:
            {     if(!isdigit(s[i]))//数字字符的判断
                 {status=1;
                  op=s[i];
                
                 }
                 else
                 {left.push_back(s[i]);
                 i++;}
                 break;
            }
            case 1:
            {   status=2;
                i++;
                break;
            }

            case 2:
             {
                 right.push_back(s[i]);
                 i++;
                 break;
             }
             
        }
        
      }

        

        return request(stoi(left),stoi(right),op);

    }
  
    ~Calclient()
    {
        if(_sock >= 0) close(_sock);
    }
    
private:
    uint16_t _serverport;
    std::string _serverip;
    int _sock;
};